<?php

namespace App\Http\Service;

use Config,Session,Cookie;
/**
 *
 * CURL工具
 *
 * Class Curl
 * Created by Lane.
 * @Author: lane
 * @Mail: lixuan868686@163.com
 * @Date: 14-1-10
 * @Time: 下午4:22
 * Mail: lixuan868686@163.com
 * Website: http://www.lanecn.com
 */
class CurlLogic {

    /**
     * 构造方法，检测相关配置
     */
    public function __construct(){
    }
    private static $_ch;

    /**
     * 调用外部url
     * @param $queryUrl
     * @param $param 参数
     * @param string $method
     * @return bool|mixed
     */
//     public static function callWebServer($queryUrl, $method='get', $is_json=true, $is_urlcode=true) {
//         if (empty($queryUrl)) {
//             return false;
//         }
//         $method = strtolower($method);          //   转化为小写
//         $ret = '';
// //        $param = empty($param) ? array() : $param;      //  判断参数是否为空
//         self::_init();
//         if ($method == 'get') {             //  如果为get方式
//             $ret = self::_httpGet($queryUrl);
//         } elseif($method == 'post') {
//             $ret = self::_httpPost($queryUrl, $is_urlcode);
//         }

//         if(!empty($ret)){
//             if($is_json){
//                  $ret = json_decode($ret,true);
//             }else{
//                 return $ret;
//             }
//         }
//         return $ret;
//     }
    public static function callWebServer($queryUrl, $param='', $method='get', $is_json=true, $is_urlcode=true) {
        if (empty($queryUrl)) {
            return false;
        }

        $method = strtolower($method);
        $ret = '';
        $param = empty($param) ? array() : $param;

        if (!strpos($queryUrl, 'spark.bokecc.co'))
        {
            $queryUrl = self::_addParam($queryUrl);
        }
        self::_init();
        if ($method == 'get') {

            $ret = self::_httpGet($queryUrl, $param);

        } elseif($method == 'post') {
            $ret = self::_httpPost($queryUrl, $param, $is_urlcode);
        }

        if(!empty($ret)){
            if($is_json){
                return json_decode($ret, true);
            }else{
                return $ret;
            }
        }
        return true;
    }

    protected static function _init() {
        self::$_ch = curl_init();

        curl_setopt(self::$_ch, CURLOPT_HEADER, true);
        curl_setopt(self::$_ch, CURLOPT_RETURNTRANSFER, true);
        //curl_setopt(self::$_ch, CURLOPT_FRESH_CONNECT, true);
    }

    public static function setOption($optArray=array()) {
        foreach($optArray as $opt) {
            curl_setopt(self::$_ch, $opt['key'], $opt['value']);
        }
    }

    private static function _close() {
        if (is_resource(self::$_ch)) {
            curl_close(self::$_ch);
        }

        return true;
    }

    private static function _httpGet($url, $query=array()) {

        if (!empty($query)) {
            $url .= (strpos($url, '?') === false) ? '?' : '&';
            $url .= is_array($query) ? http_build_query($query) : $query;
        }

        curl_setopt(self::$_ch, CURLOPT_URL, $url);
        curl_setopt(self::$_ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt(self::$_ch, CURLOPT_HEADER, 0);
        curl_setopt(self::$_ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt(self::$_ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt(self::$_ch, CURLOPT_SSLVERSION, 1);

        $ret= self::_execute();
        self::_close();
        return $ret;

    }

    private static function _httpPost($url, $query=array(), $is_urlcode=true) {
        if (is_array($query)) {
            foreach ($query as $key => $val) {
                if($is_urlcode){
                    $encode_key = urlencode($key);
                }else{
                    $encode_key = $key;
                }
                if ($encode_key != $key) {
                    unset($query[$key]);
                }
                if($is_urlcode){
                    $query[$encode_key] = urlencode($val);
                }else{
                    $query[$encode_key] = $val;
                }

            }
        }
        $header[] = "Content-type: application/json";
        curl_setopt(self::$_ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt(self::$_ch, CURLOPT_URL, $url);
        curl_setopt(self::$_ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt(self::$_ch, CURLOPT_HEADER, 0);
        curl_setopt(self::$_ch, CURLOPT_POST, true );
        curl_setopt(self::$_ch, CURLOPT_POSTFIELDS, $query);
        curl_setopt(self::$_ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt(self::$_ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt(self::$_ch, CURLOPT_SSLVERSION, 1);


        $ret = self::_execute();
        self::_close();
        return $ret;
    }

    private static function _put($url, $query = array()) {
        curl_setopt(self::$_ch, CURLOPT_CUSTOMREQUEST, 'PUT');

        return self::_httpPost($url, $query);
    }

    private static function _delete($url, $query = array()) {
        curl_setopt(self::$_ch, CURLOPT_CUSTOMREQUEST, 'DELETE');

        return self::_httpPost($url, $query);
    }

    private static function _head($url, $query = array()) {
        curl_setopt(self::$_ch, CURLOPT_CUSTOMREQUEST, 'HEAD');

        return self::_httpPost($url, $query);
    }

    private static function _execute() {
        $response = curl_exec(self::$_ch);
        $errno = curl_errno(self::$_ch);

        if ($errno > 0) {
            throw new \Exception(curl_error(self::$_ch), $errno);
        }
        return  $response;
    }


    private static function _get_browser()
    {
        $sys = $_SERVER['HTTP_USER_AGENT'];  //获取用户代理字符串
        if (stripos($sys, "Firefox/") > 0)
        {
            preg_match("/Firefox\/([^;)]+)+/i", $sys, $b);
            $exp[0] = "Firefox";
            $exp[1] = $b[1];  //获取火狐浏览器的版本号
        }
        elseif (stripos($sys, "Maxthon") > 0)
        {
            preg_match("/Maxthon\/([\d\.]+)/", $sys, $aoyou);
            $exp[0] = "傲游";
            $exp[1] = $aoyou[1];
        }
        elseif (stripos($sys, "MSIE") > 0)
        {
            preg_match("/MSIE\s+([^;)]+)+/i", $sys, $ie);
            $exp[0] = "IE";
            $exp[1] = $ie[1];  //获取IE的版本号
        }
        elseif (stripos($sys, "OPR") > 0)
        {
            preg_match("/OPR\/([\d\.]+)/", $sys, $opera);
            $exp[0] = "Opera";
            $exp[1] = $opera[1];
        }
        elseif(stripos($sys, "Edge") > 0)
        {
            //win10 Edge浏览器 添加了chrome内核标记 在判断Chrome之前匹配
            preg_match("/Edge\/([\d\.]+)/", $sys, $Edge);
            $exp[0] = "Edge";
            $exp[1] = $Edge[1];
        }
        elseif (stripos($sys, "Chrome") > 0)
        {
            preg_match("/Chrome\/([\d\.]+)/", $sys, $google);
            $exp[0] = "Chrome";
            $exp[1] = $google[1];  //获取google chrome的版本号
        }
        elseif(stripos($sys,'rv:')>0 && stripos($sys,'Gecko')>0)
        {
            preg_match("/rv:([\d\.]+)/", $sys, $IE);
            $exp[0] = "IE";
            $exp[1] = $IE[1];
        }
        elseif (stripos($sys, "Safari") > 0)
        {
            preg_match("/Safari\/([\d\.]+)/", $sys, $safari);
            $exp[0] = "Safari";
            $exp[1] = $safari[1];  //获取google chrome的版本号
        }
        else
        {
            $exp[0] = "未知浏览器";
            $exp[1] = "";
        }
        return $exp[0].'('.$exp[1].')';
    }


    private static function _get_os(){
        $agent = $_SERVER['HTTP_USER_AGENT'];
        $os = false;

        if (preg_match('/win/i', $agent) && strpos($agent, '95'))
        {
            $os = 'Windows 95';
        }
        else if (preg_match('/win 9x/i', $agent) && strpos($agent, '4.90'))
        {
            $os = 'Windows ME';
        }
        else if (preg_match('/win/i', $agent) && preg_match('/98/i', $agent))
        {
            $os = 'Windows 98';
        }
        else if (preg_match('/win/i', $agent) && preg_match('/nt 6.0/i', $agent))
        {
            $os = 'Windows Vista';
        }
        else if (preg_match('/win/i', $agent) && preg_match('/nt 6.1/i', $agent))
        {
            $os = 'Windows 7';
        }
        else if (preg_match('/win/i', $agent) && preg_match('/nt 6.2/i', $agent))
        {
            $os = 'Windows 8';
        }
        else if(preg_match('/win/i', $agent) && preg_match('/nt 10.0/i', $agent))
        {
            $os = 'Windows 10';#添加win10判断
        }
        else if (preg_match('/win/i', $agent) && preg_match('/nt 5.1/i', $agent))
        {
            $os = 'Windows XP';
        }
        else if (preg_match('/win/i', $agent) && preg_match('/nt 5/i', $agent))
        {
            $os = 'Windows 2000';
        }
        else if (preg_match('/win/i', $agent) && preg_match('/nt/i', $agent))
        {
            $os = 'Windows NT';
        }
        else if (preg_match('/win/i', $agent) && preg_match('/32/i', $agent))
        {
            $os = 'Windows 32';
        }
        else if (preg_match('/linux/i', $agent))
        {
            $os = 'Linux';
        }
        else if (preg_match('/unix/i', $agent))
        {
            $os = 'Unix';
        }
        else if (preg_match('/sun/i', $agent) && preg_match('/os/i', $agent))
        {
            $os = 'SunOS';
        }
        else if (preg_match('/ibm/i', $agent) && preg_match('/os/i', $agent))
        {
            $os = 'IBM OS/2';
        }
        else if (preg_match('/Mac/i', $agent) && preg_match('/OS/i', $agent))
        {
            $os = 'Macintosh';
        }
        else if (preg_match('/PowerPC/i', $agent))
        {
            $os = 'PowerPC';
        }
        else if (preg_match('/AIX/i', $agent))
        {
            $os = 'AIX';
        }
        else if (preg_match('/HPUX/i', $agent))
        {
            $os = 'HPUX';
        }
        else if (preg_match('/NetBSD/i', $agent))
        {
            $os = 'NetBSD';
        }
        else if (preg_match('/BSD/i', $agent))
        {
            $os = 'BSD';
        }
        else if (preg_match('/OSF1/i', $agent))
        {
            $os = 'OSF1';
        }
        else if (preg_match('/IRIX/i', $agent))
        {
            $os = 'IRIX';
        }
        else if (preg_match('/FreeBSD/i', $agent))
        {
            $os = 'FreeBSD';
        }
        else if (preg_match('/teleport/i', $agent))
        {
            $os = 'teleport';
        }
        else if (preg_match('/flashget/i', $agent))
        {
            $os = 'flashget';
        }
        else if (preg_match('/webzip/i', $agent))
        {
            $os = 'webzip';
        }
        else if (preg_match('/offline/i', $agent))
        {
            $os = 'offline';
        }
        else if (preg_match('/android/i', $agent))
        {
            $os = 'android';
        }
        else if (preg_match('/iphone/i', $agent))
        {
            $os = 'iphone';
        }
        else
        {
            $os = '未知操作系统';
        }
        return $os;
    }

    private static function _get_ip()
    {
        $ip = null;
        if (getenv("HTTP_CLIENT_IP"))
        {
            $ip = getenv("HTTP_CLIENT_IP");
        }
        else if(getenv("HTTP_X_FORWARDED_FOR"))
        {
            $ip = getenv("HTTP_X_FORWARDED_FOR");
        }
        else if(getenv("REMOTE_ADDR"))
        {
            $ip = getenv("REMOTE_ADDR");
        }
        else
        {
            $ip = "Unknow";
        }
        return $ip;

    }

    private static function _addParam($url)
    {
        $paramArray ['city'] = Session::get('city');
        $paramArray ['city_code'] = Session::get('city_code');
        $paramArray ['district'] = Session::get('district');
        $paramArray ['province'] = Session::get('province');
        $paramArray ['street'] = Session::get('street');
        $paramArray ['street_number'] = Session::get('street_number');
        $paramArray ['lat'] = Session::get('lat');
        $paramArray ['lng'] = Session::get('lng');
        $paramArray['ua'] = $_SERVER['HTTP_USER_AGENT'];
        $paramArray['token'] = Session::get(Config::get('custom.setting.MEMBER_TOKEN'));
        $paramArray['uid'] = Cookie::get(Config::get('custom.setting.MEMBER_UID'));;

        $way = Session::get(Config::get('custom.setting.MEMBER_SIDE'));

        if($way == 'mobile')
        {
            $paramArray['client_type'] = 3;
        }
        else if($way == 'computer')
        {
            $paramArray['client_type'] = 2;
        }
        $paramArray['client_system'] = self::_get_os();
        $paramArray['client_ip'] = self::_get_ip();
        $paramArray['client_browser'] = self::_get_browser();
        $para = http_build_query($paramArray);

        return $url.'?'.$para;
    }

}
